package cn.sdhuijin.healthexam.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import cn.sdhuijin.healthexam.bean.UserInfoBean;

import com.ivsign.android.IDCReader.IDCReaderSDK;

public class ConnectBluetooth {
	// TAG打印LOG
	private static final String TAG = "ConnectBluetooth";
	// 蓝牙设备名称
	private static final String DEVICE_NAME1 = "CVR-100B";
	private static final String DEVICE_NAME2 = "IDCReader";
	private static final String DEVICE_NAME3 = "COM2";
	private static final String DEVICE_NAME4 = "BOLUTEK";
	// 蓝牙ID
	UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	// 蓝牙设备Adapter
	private BluetoothAdapter bluetoothAdapter;
	// 服务端Socket
	private BluetoothServerSocket bluetoothServerSocket;
	// 客户端Socket
	private BluetoothSocket bluetoothSocket;
	private InputStream inputStream;
	private OutputStream outputStream = null;
	// 连接结果
	int Readflage = -99;

	byte[] cmd_SAM = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x03, 0x12, (byte) 0xFF, (byte) 0xEE };
	byte[] cmd_find = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x03, 0x20, 0x01, 0x22 };
	byte[] cmd_selt = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x03, 0x20, 0x02, 0x21 };
	byte[] cmd_read = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x03, 0x30, 0x01, 0x32 };
	byte[] cmd_sleep = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x02, 0x00, 0x02 };
	byte[] cmd_weak = { (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
			0x69, 0x00, 0x02, 0x01, 0x03 };
	byte[] recData = new byte[1500];
	// 身份证信息数组
	String[] decodeInfo = new String[10];

	public ConnectBluetooth() {

	}

	/**
	 * 获取蓝牙设备连接
	 * 
	 * @return 连接结果
	 */
	public boolean getBluetoothConnect() {
		Log.i(TAG, "开始蓝牙连接");
		// 连接结果
		boolean result = false;
		// 获取蓝牙连接
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		// 查看可连接蓝牙设备
		Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter
				.getBondedDevices();
		if (bluetoothDevices.size() > 0) {
			for (Iterator<BluetoothDevice> iterator = bluetoothDevices
					.iterator(); iterator.hasNext();) {
				// 获取绑定设备名称
				BluetoothDevice device = (BluetoothDevice) iterator.next();
				// 绑定设备名称
				String deviceName = device.getName();
				// 通过绑定设备名称判断是否为指定设备
				if (DEVICE_NAME1.equals(deviceName)
						|| DEVICE_NAME2.equals(deviceName)
						|| DEVICE_NAME3.equals(deviceName)
						|| DEVICE_NAME4.equals(deviceName)) {
					try {
						// 蓝牙开启
						bluetoothAdapter.enable();
						// 使蓝牙处于可发现模式
						Intent intent = new Intent(
								BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
						// 持续时间150秒
						intent.putExtra(
								BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
								150);
						// 获取sdk版本
						int sdk = Integer.parseInt(Build.VERSION.SDK);
						if (sdk >= 10) {
							bluetoothSocket = device
									.createInsecureRfcommSocketToServiceRecord(MY_UUID);
						} else {
							bluetoothSocket = device
									.createRfcommSocketToServiceRecord(MY_UUID);
						}
						// 服务端Socket
						bluetoothServerSocket = bluetoothAdapter
								.listenUsingRfcommWithServiceRecord(
										"myServerSocket", MY_UUID);
						bluetoothSocket.connect();
						inputStream = bluetoothSocket.getInputStream();
						outputStream = bluetoothSocket.getOutputStream();
					} catch (IOException e) {
						// TODO: handle exception
						Log.e(TAG, "蓝牙连接异常");
						e.printStackTrace();
					}
					if (inputStream != null && outputStream != null) {
						Log.i(TAG, "蓝牙连接成功");
						result = true;
					} else {
						Log.e(TAG, "蓝牙连接失败");
						result = false;
					}
				}

			}
		}
		return result;
	}

	/**
	 * 获取身份证读取设备连接读取信息
	 * 
	 * @return 身份证信息
	 */
	public UserInfoBean readIdentifyInfo() {
		// 身份证信息
		UserInfoBean UserInfoBean = null;
		// 读取次数，默认15次
		int readcount = 15;
		try {
			while (readcount > 1) {
				// 开始读取身份证信息
				beginReadCard();
				readcount = readcount - 1;
				// 读取信息成功
				if (Readflage > 0) {
					readcount = 0;
					UserInfoBean = new UserInfoBean();
					// 姓名
					UserInfoBean.setUserName(decodeInfo[0]);
					// 性别
					UserInfoBean.setUserSex(decodeInfo[1]);
					// 民族
					UserInfoBean.setUserNation(decodeInfo[2]);
					// 出生日期
					UserInfoBean.setUserBirth(Util.dateFormat(decodeInfo[3]));
					// 地址
					UserInfoBean.setUserAddress(decodeInfo[4]);
					// 身份证号
					UserInfoBean.setIdenfyCardNum(decodeInfo[5]);
					// 签发机关
					UserInfoBean.setFromDepartment(decodeInfo[6]);
					// 有限期限
					UserInfoBean.setExpiryDate(decodeInfo[7] + "-"
							+ decodeInfo[8]);
					if (Readflage == 1) {
						// 身份证照片
						Bitmap bitmap = BitmapFactory.decodeFile(Environment
								.getExternalStorageDirectory()
								+ "/wltlib/zp.bmp");
						UserInfoBean.setUserPhoto(bitmap);
					} else {
						Log.e(TAG,
								"照片解码失败，请检查路径 "
										+ Environment
												.getExternalStorageDirectory()
										+ "/wltlib/");
					}
				} else if (Readflage == -2) {
					Log.i(TAG, "蓝牙连接异常");
				} else if (Readflage == -3 || Readflage == -4) {
					Log.i(TAG, "无卡或卡片已读过");
				} else if (Readflage == -5) {
					Log.i(TAG, "读卡失败");
				} else if (Readflage == -99) {
					Log.i(TAG, "操作异常");
				}
				Thread.sleep(100);
			}
		} catch (InterruptedException e) {
			// TODO: handle exception
			Log.e(TAG, "读取数据异常");
			e.printStackTrace();
		}
		return UserInfoBean;
	}

	/**
	 * 读取身份证信息
	 */
	public void beginReadCard() {
		try {
			if ((inputStream == null) || (outputStream == null)) {
				// 连接异常
				Readflage = -2;
				return;
			}
			outputStream.write(cmd_find);
			Thread.sleep(200);
			int datalen = inputStream.read(recData);
			if (recData[9] == -97) {
				outputStream.write(cmd_selt);
				Thread.sleep(200);
				datalen = inputStream.read(recData);
				if (recData[9] == -112) {
					outputStream.write(cmd_read);
					Thread.sleep(1000);
					byte[] tempData = new byte[1500];
					if (inputStream.available() > 0) {
						datalen = inputStream.read(tempData);
					} else {
						Thread.sleep(500);
						if (inputStream.available() > 0) {
							datalen = inputStream.read(tempData);
						}
					}
					int flag = 0;
					if (datalen < 1294) {
						for (int i = 0; i < datalen; i++, flag++) {
							recData[flag] = tempData[i];
						}
						Thread.sleep(1000);
						if (inputStream.available() > 0) {
							datalen = inputStream.read(tempData);
						} else {
							Thread.sleep(500);
							if (inputStream.available() > 0) {
								datalen = inputStream.read(tempData);
							}
						}
						for (int i = 0; i < datalen; i++, flag++) {
							recData[flag] = tempData[i];
						}

					} else {
						for (int i = 0; i < datalen; i++, flag++) {
							recData[flag] = tempData[i];
						}
					}
					tempData = null;
					if (flag == 1295) {
						if (recData[9] == -112) {

							byte[] dataBuf = new byte[256];
							for (int i = 0; i < 256; i++) {
								dataBuf[i] = recData[14 + i];
							}
							String TmpStr = new String(dataBuf, "UTF16-LE");
							TmpStr = new String(TmpStr.getBytes("UTF-8"));
							decodeInfo[0] = TmpStr.substring(0, 15);
							decodeInfo[1] = TmpStr.substring(15, 16);
							decodeInfo[2] = TmpStr.substring(16, 18);
							decodeInfo[3] = TmpStr.substring(18, 26);
							decodeInfo[4] = TmpStr.substring(26, 61);
							decodeInfo[5] = TmpStr.substring(61, 79);
							decodeInfo[6] = TmpStr.substring(79, 94);
							decodeInfo[7] = TmpStr.substring(94, 102);
							decodeInfo[8] = TmpStr.substring(102, 110);
							decodeInfo[9] = TmpStr.substring(110, 128);
							if (decodeInfo[1].equals("1"))
								decodeInfo[1] = "男";
							else
								decodeInfo[1] = "女";
							try {
								int code = Integer.parseInt(decodeInfo[2]
										.toString());
								decodeInfo[2] = decodeNation(code);
							} catch (Exception e) {
								decodeInfo[2] = "";
							}

							// 照片解码
							try {
								int ret = IDCReaderSDK.Init();
								if (ret == 0) {
									byte[] datawlt = new byte[1384];
									byte[] byLicData = { (byte) 0x05,
											(byte) 0x00, (byte) 0x01,
											(byte) 0x00, (byte) 0x5B,
											(byte) 0x03, (byte) 0x33,
											(byte) 0x01, (byte) 0x5A,
											(byte) 0xB3, (byte) 0x1E,
											(byte) 0x00 };
									for (int i = 0; i < 1295; i++) {
										datawlt[i] = recData[i];
									}
									int t = IDCReaderSDK.unpack(datawlt,
											byLicData);
									if (t == 1) {
										Readflage = 1;// 读卡成功
									} else {
										Readflage = 6;// 照片解码异常
									}
								} else {
									Readflage = 6;// 照片解码异常
								}
							} catch (Exception e) {
								Readflage = 6;// 照片解码异常
							}

						} else {
							Readflage = -5;// 读卡失败！
						}
					} else {
						Readflage = -5;// 读卡失败
					}
				} else {
					Readflage = -4;// 选卡失败
				}
			} else {
				Readflage = -3;// 寻卡失败
			}

		} catch (IOException e) {
			Readflage = -99;// 读取数据异常
		} catch (InterruptedException e) {
			Readflage = -99;// 读取数据异常
		}
	}

	public String decodeNation(int code) {
		String nation;
		switch (code) {
		case 1:
			nation = "汉";
			break;
		case 2:
			nation = "蒙古";
			break;
		case 3:
			nation = "回";
			break;
		case 4:
			nation = "藏";
			break;
		case 5:
			nation = "维吾尔";
			break;
		case 6:
			nation = "苗";
			break;
		case 7:
			nation = "彝";
			break;
		case 8:
			nation = "壮";
			break;
		case 9:
			nation = "布依";
			break;
		case 10:
			nation = "朝鲜";
			break;
		case 11:
			nation = "满";
			break;
		case 12:
			nation = "侗";
			break;
		case 13:
			nation = "瑶";
			break;
		case 14:
			nation = "白";
			break;
		case 15:
			nation = "土家";
			break;
		case 16:
			nation = "哈尼";
			break;
		case 17:
			nation = "哈萨克";
			break;
		case 18:
			nation = "傣";
			break;
		case 19:
			nation = "黎";
			break;
		case 20:
			nation = "傈僳";
			break;
		case 21:
			nation = "佤";
			break;
		case 22:
			nation = "畲";
			break;
		case 23:
			nation = "高山";
			break;
		case 24:
			nation = "拉祜";
			break;
		case 25:
			nation = "水";
			break;
		case 26:
			nation = "东乡";
			break;
		case 27:
			nation = "纳西";
			break;
		case 28:
			nation = "景颇";
			break;
		case 29:
			nation = "柯尔克孜";
			break;
		case 30:
			nation = "土";
			break;
		case 31:
			nation = "达斡尔";
			break;
		case 32:
			nation = "仫佬";
			break;
		case 33:
			nation = "羌";
			break;
		case 34:
			nation = "布朗";
			break;
		case 35:
			nation = "撒拉";
			break;
		case 36:
			nation = "毛南";
			break;
		case 37:
			nation = "仡佬";
			break;
		case 38:
			nation = "锡伯";
			break;
		case 39:
			nation = "阿昌";
			break;
		case 40:
			nation = "普米";
			break;
		case 41:
			nation = "塔吉克";
			break;
		case 42:
			nation = "怒";
			break;
		case 43:
			nation = "乌孜别克";
			break;
		case 44:
			nation = "俄罗斯";
			break;
		case 45:
			nation = "鄂温克";
			break;
		case 46:
			nation = "德昂";
			break;
		case 47:
			nation = "保安";
			break;
		case 48:
			nation = "裕固";
			break;
		case 49:
			nation = "京";
			break;
		case 50:
			nation = "塔塔尔";
			break;
		case 51:
			nation = "独龙";
			break;
		case 52:
			nation = "鄂伦春";
			break;
		case 53:
			nation = "赫哲";
			break;
		case 54:
			nation = "门巴";
			break;
		case 55:
			nation = "珞巴";
			break;
		case 56:
			nation = "基诺";
			break;
		case 97:
			nation = "其他";
			break;
		case 98:
			nation = "外国血统中国籍人士";
			break;
		default:
			nation = "";
			break;
		}
		return nation;
	}

	/**
	 * 关闭蓝牙连接
	 */
	public void closeBlueToothConn() {
		try {
			if (inputStream == null || outputStream == null) {
				return;
			} else {
				if (inputStream != null) {
					inputStream.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
				if (bluetoothSocket != null) {
					bluetoothSocket.close();
				}
				if (bluetoothServerSocket != null) {
					bluetoothServerSocket.close();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "关闭蓝牙连接异常");
			e.printStackTrace();
		}
	}
}
